<?php

/**
 * User:ayou chow
 * Date: 2019-12-09
 * Time: 15:52
 */

namespace app\admin\controller;


use app\common\Esclient;
use app\common\model\AdsModel;
use app\common\model\ChatLogModel;
use app\common\model\ConfigPubModel;
use app\common\model\LiveModel;
use app\common\model\LiveRoomBanneduserModel;
use app\common\model\UserLevelRuleModel;
use app\common\model\UserModel;
use app\common\model\AutoPushModel;
use app\service\ChatService;
use gogrpc\LiveServer;
use think\facade\Request;

class ChatController extends BaseController
{
    public $blackById = "BlackUid_%s";


    public function Log()
    {
        $anchor_id = Request::get('anchor_id');

        $rule  = ConfigPubModel::where(['id' => 1])->find()->chat_rule;
        $rule  = json_decode($rule, true);
        $count = count($rule);

        $this->assign('anchor_id', $anchor_id);
        $this->assign('rule', $rule);
        $this->assign('count', $count);
        return $this->fetch();
    }

    public function appadd()
    {
        return $this->fetch();
    }

    public function appedit()
    {
        $ads = ChatLogModel::get(Request::param('id'));
        $this->assign("adsInfo", $ads);
        return $this->fetch();
    }

    public function signForCos()
    {
        return parent::signForCos();
    }

    public function getlist()
    {
        $uid       = Request::param('uid', false);
        $mobile    = Request::param('mobile', false);
        $room_id   = Request::param('room_id', false);
        $nick_name = Request::param('nick_name', false);
        $page      = Request::param("page");
        $limit     = Request::param("limit");

        // es查询条件
        $options = [
            'index' => 'es_chat_history',
            'size'  => $limit,
            'from'  => ($page - 1) * $limit,
            'sort'  => ['create_time' => 'desc'],
            'where' => [],
        ];

        // 从那个id开始查询
        if ($room_id) {
            $options['where'][] = ['room_id', '=', is_numeric($room_id) ? $room_id : 0];
        }
        if ($uid) {
            $options['where'][] = ['user_id', '=', is_numeric($uid) ? $uid : 0];
        }

        if ($nick_name) {
            $search_uid         = UserModel::whereLike('nick_name', "%{$nick_name}%")->column('id');
            $options['where'][] = ['user_id', 'IN', $search_uid];
        }

        if ($mobile) {
            $search_uid         = UserModel::whereLike('mobile', "%{$mobile}%")->column('id');
            $options['where'][] = ['user_id', 'IN', $search_uid];
        }

        try {
            // 获取数据
            $es_client = new Esclient();
            $response  = $es_client->search($options);

            $data  = $response['data'];
            $count = $response['total'];

            if ($data) {
                // 查询等级列表
                $level_list = UserLevelRuleModel::select();

                $uid_arr = array_column($data, 'user_id');
                $uid_arr = array_unique(array_filter($uid_arr));

                // 角色id
                $admin_roleid = $this->userinfo->roleid;

                $user_list = UserModel::with([
                    'nobleRecord' => function ($query) {
                        $where = [
                            ['expiration', '>=', time()]
                        ];
                        $query->where($where)->order('id desc')->limit(1);
                    }
                ])
                    ->whereIn('id', $uid_arr)
                    ->field('id,mobile,nick_name,point')
                    ->select()
                    ->each(function ($query) use ($level_list, $admin_roleid) {
                        $query->mobile = mobileHide($query->mobile, $admin_roleid);
                        // 用户等级计算
                        foreach ($level_list as $level_info) {
                            if ($query->point < 1) {
                                $query->user_level = 0;
                                break;
                            }
                            if ($query->point == $level_info->point) {
                                $query->user_level = $level_info->level;
                                break;
                            }

                            if ($query->point > $level_info->point) {
                                $query->user_level = $level_info->level;
                            }

                            foreach ($level_list as $level_two) {
                                if ($query->point == $level_two->point) {
                                    $query->user_level = $level_two->level;
                                    break;
                                } else if ($query->point >= $level_info->point && $query->point < $level_two->point) {
                                    $query->user_level = $level_info->level;
                                    break;
                                }
                            }
                        }

                        $query->nobel_str = !empty($query->noble_record->noble) ? $query->noble_record->noble->name : '';
                    })->toArray();

                $user_list = array_column($user_list, null, 'id');


                // 禁用的用户
                $banned_user = LiveRoomBanneduserModel::with('mgruser')->whereIn('uid', $uid_arr)
                    ->where('ban_time', '>=', time())
                    ->select()->toArray();

                foreach ($data as &$item) {
                    $user_info = isset($item['user_id']) && !empty($user_list[$item['user_id']]) ? $user_list[$item['user_id']] : [];

                    $item['mobile']        = isset($user_info['mobile']) ? $user_info['mobile'] : '';
                    $item['nick_name']     = isset($user_info['nick_name']) ? $user_info['nick_name'] : '';
                    $item['user_level']    = isset($user_info['user_level']) ? $user_info['user_level'] : 0;
                    $item['nobel_str']     = isset($user_info['nobel_str']) ? $user_info['nobel_str'] : '';
                    $item['create_time_t'] = $item['create_time'];
                    // 屏蔽状态，1正常，0屏蔽
                    $item['status'] = isset($item['status']) ? $item['status'] : 1;

                    // 禁言状态
                    foreach ($banned_user as $val) {
                        if($val['uid'] == 1) {
                            continue;
                        }
                        // 所有房间
                        if ($val['anchorid'] == 0 && isset($item['user_id']) && $val['uid'] == $item['user_id']) {
                            $item['bannedid']       = $val['id'];
                            $item['bannerd_status'] = 2;
                            if ($val['mgrid'] == 0 && $val['admin_id'] > 0) {
                                $item['mgrname'] = '超管';
                            } else {
                                $item['mgrname'] = isset($val['mgruser']) ? $val['mgruser']['nick_name'] : '';
                            }
                        }

                        // 某一个房间
                        if ($val['anchorid'] == $item['room_id'] && isset($item['user_id']) && $val['uid'] == $item['user_id']) {
                            $item['bannedid']       = $val['id'];
                            $item['bannerd_status'] = 2;
                            if ($val['mgrid'] == 0 && $val['admin_id'] > 0) {
                                $item['mgrname'] = '超管';
                            } else {
                                $item['mgrname'] = isset($val['mgruser']) ? $val['mgruser']['nick_name'] : '';
                            }
                        }
                    }

                    if (!empty($item['create_time'])) {
                        if (strlen($item['create_time']) > 10) {
                            $item['create_time'] = intval($item['create_time'] / 1000);
                        }
                        $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                    } else {
                        $item['create_time'] = '';
                    }
                }
            }

            if ($count > 0) {
                return json(["code" => 0, "msg" => "", "data" => $data, "count" => $count]);
            }
        } catch (\Exception $e) {
            return self::bulidDataFail(['error' => $e->getMessage()], '查询异常');
        }
        return self::bulidFail("未查询到相关数据");
    }

    public function appadd_post()
    {
        $ads              = new AdsModel(Request::param());
        $ads->create_time = date("Y-m-d H:i:s");
        if ($ads->save()) {
            return self::bulidSuccess([]);
        }
        return self::bulidFail();
    }

    public function edit_post()
    {
        ConfigPubModel::where(['id' => 1])
            ->update(['chat_rule' => Request::param('data', '')]);
        return self::bulidSuccess([]);
    }


    /**
     * 直播间聊天日志监控
     */
    public function live_chat()
    {
        // 查询直播列表
        $page  = Request::param('page') ?? 1;
        $limit = 12;
        $where = ['status' => 1];

        $lives = LiveModel::with('anchor')
            ->where($where)
            ->order(['hot' => 'desc'])
            ->limit(($page - 1) * $limit, $limit)
            ->select();
        $count = LiveModel::where($where)->count();

        $this->assign('lives', $lives);
        $this->assign('page', $page);
        $this->assign('limit', $limit);
        $this->assign('count', $count);

        return $this->fetch();
    }

    /**
     * 直播聊天监控日志列表
     * @return \think\response\Json
     */
    public function get_live_chat()
    {
        // 每个直播间最新显示的一条创建时间
        $chat_time = Request::param('chat_time', 0);
        $room_id   = Request::param('room_id', 0);
        $page      = Request::param("page", 1);
        $limit     = Request::param("limit", 20);

        if ($room_id < 1) {
            return parent::bulidSuccess();
        }

        // 查询消息屏蔽
        $shield_data = ChatService::getChatShield($room_id);
        $shield_data = array_column($shield_data, 'id');

        // 查询禁言用户
        $b_where        = "(anchorid = {$room_id} or anchorid=0) AND ban_time>" . time();
        $band_user      = LiveRoomBanneduserModel::with('mgruser')->where($b_where)->group('uid')->select();
        $room_band_user = [];
        foreach ($band_user as $val) {
            if($val->uid == 1){
                continue;
            }
            $data                   = [];
            $data['bannedid']       = $val->id;
            $data['anchorid']       = $val->anchorid;
            $data['uid']            = $val->uid;
            $data['bannerd_status'] = 2;
            $data['mgrid']          = $val->mgrid;
            if ($val->mgrid == 0 && $val->admin_id > 0) {
                $data['mgrname'] = '超管';
            } else {
                $data['mgrname'] = !empty($val->mgruser) ? $val->mgruser->nick_name : '';
            }
            $room_band_user[] = $data;
            unset($val, $data);
        }

        // 首次请求加载50条数据
        $limit = $chat_time < 1 ? 100 : $limit;

        // es查询条件
        $options = [
            'index' => 'es_chat_history',
            'size'  => $limit,
            'from'  => ($page - 1) * $limit,
            'sort'  => ['create_time' => 'desc'],
            'where' => [
                ['room_id', '=', $room_id],
            ],
        ];
        // 从那个时间开始查询
        if ($chat_time) {
            $options['where'][] = ['create_time', '>', $chat_time];
        }

        // 获取数据
        $es_client = new Esclient();
        $response  = $es_client->search($options);
        $data      = $response['data'];
        $count     = $response['total'];

        if ($count > 0) {
            $uid_arr = array_column($data, 'user_id');
            $uid_arr = array_unique(array_filter($uid_arr));

            $user_list = UserModel::whereIn('id', $uid_arr)->field('id,nick_name')->select()->toArray();
            $user_list = array_column($user_list, 'nick_name', 'id');

            foreach ($data as &$item) {
                // 屏蔽状态
                if (!isset($item['status'])) {
                    $item['status'] = 1;
                }
                $item['bannerd_status'] = 1;
                // 用户封禁状态，-1未封禁，0=超管，>0房管
                $item['mgrid']           = -1;
                $item['mgrname']         = '';
                $item['nick_name']       = isset($item['user_id']) && !empty($user_list[$item['user_id']]) ? $user_list[$item['user_id']] : '';
                $item['bannedid']        = 0;
                $item['create_time_str'] = '';

                if (!empty($item['create_time'])) {
                    if (strlen($item['create_time']) > 10) {
                        $item['create_time_str'] = date('Y-m-d H:i:s', (intval($item['create_time'] / 1000)));
                    } else {
                        $item['create_time_str'] = date('Y-m-d H:i:s', $item['create_time']);
                    }
                }
            }
        }
        return json(["code" => 0, "msg" => "", "data" => $data, 'band_user' => $room_band_user, 'shield' => $shield_data, 'uptime' => date('Y-m-d H:i:s')]);
    }


    /**
     * 屏蔽发言
     */
    public function shield_speak()
    {
        $id      = Request::param('id', 0);
        $room_id = Request::param('room_id', 0);
        if ($id < 1 || $room_id < 1) {
            return parent::bulidFail('参数错误');
        }
        $data = ChatService::getChatInfoById($id, $room_id);
        if (empty($data)) {
            return parent::bulidFail('未查询到相关聊天信息');
        }

        $live_server = new LiveServer();
        $res         = $live_server->clearChatAdmin($id, $data['user_id'], $data['room_id']);
        if (!$res) {
            return static::bulidFail('屏蔽失败');
        }

        // 修改
        $params = [
            'index' => 'es_chat_history',
            'id'    => $data['room_id'] . '_' . $id,
            'body'  => [
                'doc' => [
                    'status' => 0
                ]
            ]
        ];
        // 获取数据
        $es_client = new Esclient();
        $is_res    = $es_client->update($params);
        if (!$is_res) {
            return parent::bulidFail('屏蔽失败');
        }
        // 记录日志
        $log_content = "屏蔽用户发言，用户ID：{$data['user_id']}，发言内容：{$data['content']}";
        parent::addAdminLog($log_content, $data['user_id']);

        return parent::bulidSuccess([], '屏蔽成功');
    }


    public function shield()
    {
        $id      = Request::param('id', 0);
        $room_id = Request::param('room_id', 0);
        if ($id < 1 || $room_id < 1) {
            return parent::bulidFail('参数错误');
        }

        $data = ChatService::getChatInfoById($id, $room_id);
        if (empty($data)) {
            return parent::bulidFail('未查询到相关聊天信息');
        }

        $user = UserModel::where("id", $data['user_id'])->find();

        if (!$user) {
            $this->error('用户信息不存在');
        }

        $nobel_str = [];
        if (!empty($user->noble_record)) {
            foreach ($user->noble_record as $v) {
                if ($v->noble) {
                    array_push($nobel_str, $v->noble->name);
                }
            }
        }
        $user->nobel_str = implode(' ', $nobel_str);
        unset($user->noble_record);

        // 用户等级计算
        $user->user_level = UserLevelRuleModel::getUserLevel($user->point);

        return view("shield", [
            "userinfo"     => $user,
            "id"           => $id,
            "room_id"      => $room_id,
            "chat_content" => $data['content'],
        ]);
    }

    public function admin_pub()
    {
        $id = Request::param('room_id', 0);
        $content = Request::param('content');
        $name = Request::param('name');
        if ($id < 1 || strlen($content) < 1) {
            return parent::bulidFail('参数错误');
        }
        $live_server = new LiveServer();
        $res         = $live_server->adminPub($id, $content, $name);
        if (!$res) {
            return static::bulidFail('发送成功');
        }
    }

    public function admin_pub_all()
    {
        $content = Request::param('content');
        $lives = LiveModel::where("status", 1)->select();
        $live_server = new LiveServer();
        foreach ($lives as $key => $value) {
            $live_server->adminPub($value['anchorid'], $content, "超管");
        }
        return static::bulidFail('发送成功');
    }

    public function reply()
    {
        $room_id = Request::param("room_id");
        $user = Request::param("user");

        $this->assign("room_id", $room_id);
        $this->assign("user", $user);

        return $this->fetch();
    }

    public function reply_pub()
    {
        $id = Request::param('room_id', 0);
        $content = Request::param('content');
        $name = Request::param('name');
        $user = Request::param('user');

        if ($id < 1 || strlen($content) < 1) {
            return parent::bulidFail('参数错误');
        }

        $content = "[回复] {$user}: " . $content;
        $live_server = new LiveServer();
        $res         = $live_server->adminPub($id, $content, $name);
        if (!$res) {
            return static::bulidFail('发送失败');
        }
        return parent::bulidSuccess([], '发送成功');
    }

    public function auto_push()
    {
        $data = [];
        $data = AutoPushModel::get(1);
        $this->assign("data", $data);

        return $this->fetch();
    }

    public function auto_push_config()
    {
        $interval = Request::param('interval');
        $link = Request::param('link');
        $content = Request::param('content');

        if (AutoPushModel::where("id", 1)->update(['link' => $link, 'content' => $content, 'interval' => $interval])) {
            return parent::bulidSuccess([], '保存成功');
        }

        return static::bulidFail('保存失败');
    }
}
